'use strict';
const server = require('../../server');

module.exports = function(Position) {
    Position.findOrgByUserId = function (query, response) {
        let newQueryObj = {
            "include":{
                "relation": "org",
            },
            "where":{
                userId: query
            },
        };
        Position.find(newQueryObj, function(err, positionData){
            if(err){
                response(err);
            }
            else{
                //找到自己的科室信息，（organization_type等于1）
                const Organization = server.models.Organization;
                
                Organization.find({include:"parent"},function(err, orgData){
                    if(err){
                        response(err);
                    }
                    else{
                        let data = positionData.map((posi,i)=>{
                            posi = posi.toJSON();
                            posi.depart = findDepart(posi.org,orgData);
                            return posi;
                        })
                        response(null,data);
                    }
                })
                
            }
        })
    };
    Position.remoteMethod(
        "findOrgByUserId",
         {
             description: 'Query the all positions by the query.',
             accepts: [
                 {arg: 'query', type: 'string', required: true, http: {source: 'path'}}
             ],
             returns: {type: 'array', root: true},
             http: {verb: 'GET', path: '/findOrgByUserId/:query'}
         }
     );

     function findDepart(org,orgData){
        org = org?org:{};
        if(org.organization_type === '1' || org.organization_type === '0'){
            return org;
        }
        else{
            let newOrg = orgData.find((item)=> {
                item = item.toJSON();
                if(item.id.toString() === org.parentId.toString()){
                    return item;
                }
            });
            if(newOrg.organization_type === '1' || newOrg.organization_type === '0'){
                return newOrg;
            }
            else{   
                findDepart(newOrg, orgData);
            }
        }
    }
};
